package com.gong.gongcloudpicture1.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.gong.gongcloudpicture1.config.CosClientConfig;
import com.gong.gongcloudpicture1.exception.BusinessException;
import com.gong.gongcloudpicture1.exception.ErrorCode;
import com.gong.gongcloudpicture1.exception.ThrowUtils;
import com.gong.gongcloudpicture1.manager.CosManager;
import com.gong.gongcloudpicture1.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 图片上传模板 - 抽象类
 */
@Slf4j
public abstract class PictureUploadTemplate {



    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;





    /**
     * 校验输入源(本地文件或者url)
     * @param inputSource
     */
    protected abstract void checkPicture(Object inputSource);

    /**
     * 获取输入源的原始文件名
     * @param inputSource
     * @return
     */
    protected abstract String getOriginalFilename(Object inputSource);

    /**
     * 处理输入源并生成本地临时文件
     * @param inputSource
     * @param file
     */
    protected abstract void processFile(Object inputSource, File file) throws Exception;





    /**
     * 上传文件
     * @param inputSource 需要上传的文件
     * @param uploadPathPrefix 文件路径前缀
     * @return
     */
    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        //1 校验图片
        checkPicture(inputSource);
        //2 制定图片上传地址
        String uuId = RandomUtil.randomString(16);
        String filename = getOriginalFilename(inputSource);
        String currentDate = DateUtil.formatDate(new Date());
        //得到最终的上传路径, 文件名以及文件尾缀, 不能使用中文, 避免路径解析错误
        String filePathName = String.format("%s_%s", currentDate, uuId);
        //uploadPathPrefix该参数是区分不同用户数上传的图片, 每个用户都有自己的一个文件夹
        String filePath = String.format("%s/%s.%s", uploadPathPrefix, filePathName, FileUtil.extName(filename));
        //返回解析结果
        File file = null;
        try {
            //3 将multipartFile转换成一个临时文件
            file = File.createTempFile(filePath, null);
            //4 处理来源文件
            processFile(inputSource, file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(filePath, file);
            //5 获取图片信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            //获取图片处理结果
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if (CollUtil.isNotEmpty(objectList)) {
                //因为只处理一条数据, 默认取第一条
                //获取压缩之后的文件信息
                CIObject ciObject = objectList.get(0);
                return buildResult(filePathName, ciObject);
            }
            return buildResult(imageInfo, filePath, file, filePathName);
        } catch (Exception e) {
            log.error("图片上传到存储对象失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally {
            //6 删除临时文件
            deleteTempFile(file);
        }
    }

    /**
     * 封装返回对象
     * @param filePathName 对象属性的返回信息
     * @param ciObject 对象属性的返回信息
     * @return
     */
    private UploadPictureResult buildResult(String filePathName, CIObject ciObject) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        //路径是COS host+上传路径
        int height = ciObject.getHeight();
        int width = ciObject.getWidth();
        //计算宽高比, 宽 / 高 保留两位小数
        double scale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + ciObject.getKey());
        uploadPictureResult.setPicHeight(height);
        uploadPictureResult.setPicWidth(width);
        uploadPictureResult.setPicSize(ciObject.getSize().longValue());
        uploadPictureResult.setPicName(FileUtil.mainName(filePathName));
        uploadPictureResult.setPicScale(scale);
        uploadPictureResult.setPicFormat(ciObject.getFormat());
        return uploadPictureResult;
    }


    /**
     * 封装返回对象
     * @param imageInfo 对象属性的返回信息
     * @param filePath
     * @param file
     * @param filePathName
     * @return
     */
    private UploadPictureResult buildResult(ImageInfo imageInfo, String filePath, File file, String filePathName) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        //路径是COS host+上传路径
        int height = imageInfo.getHeight();
        int width = imageInfo.getWidth();
        //计算宽高比, 宽 / 高 保留两位小数
        double scale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();
        uploadPictureResult.setUrl(cosClientConfig.getHost() + filePath);
        uploadPictureResult.setPicHeight(height);
        uploadPictureResult.setPicWidth(width);
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setPicName(FileUtil.mainName(filePathName));
        uploadPictureResult.setPicScale(scale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        return uploadPictureResult;
    }


    /**
     * 删除临时文件
     * @param file
     */
    public static void deleteTempFile(File file) {
        if (file != null) {
            boolean delete = file.delete();
            if (!delete) {
                log.error("file delete error" + file.getAbsolutePath());
            }
        }
    }




}
